import BaseUtil from '@/BaseUtil';
import SelectUtil from '@/SelectUtil';
import UnitCommon from '../Common/UnitCommon';

// 原理是判断上一个位置和下一个位置的距离是否超过一定的大小，判断是否需要启用突破系统

const MIN_SPEED = 500;
const MAX_SPEED = 2088;

export default class ModSpeedSystem {
    static table: Map<number, number[]> = new Map();
    constructor() {
        BaseUtil.onTimer(0.04, ModSpeedSystem.action);
    }
    static action() {
        SelectUtil.forAllAliveUnits(ModSpeedSystem.moveUnit);
        return true;
    }
    static moveUnit(u: unit) {
        let sp = UnitCommon.取总移动速度(u);
        if (sp <= 522) return;
        if (IsUnitPaused(u) || GetUnitAbilityLevel(u, 'BSTN') > 0 || GetUnitAbilityLevel(u, 'BPSE') > 0) return;

        let point = ModSpeedSystem.table[GetHandleId(u)];
        if (point == null) {
            point = ModSpeedSystem.table[GetHandleId(u)] = [GetUnitX(u), GetUnitY(u)];
        }
        let [lastX, lastY] = point;
        let cx = GetUnitX(u);
        let cy = GetUnitY(u);

        let dx = cx - lastX;
        let dy = cy - lastY;
        ModSpeedSystem.table[GetHandleId(u)] = [cx, cy];

        let dist = SquareRoot(dx * dx + dy * dy) * 25;
        if (dist >= MIN_SPEED && dist <= MAX_SPEED) {
            let rate = (sp - 522) / dist;
            let x = cx + dx * rate;
            let y = cy + dy * rate;
            SetUnitX(u, x);
            SetUnitY(u, y);
            ModSpeedSystem.table[GetHandleId(u)] = [x, y];
        }
    }
}
